package middleware

import (
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
	"goserver/internal/service"
)

type AuthMiddleware struct {
	tokenService *service.TokenService
}

func NewAuthMiddleware(tokenService *service.TokenService) *AuthMiddleware {
	return &AuthMiddleware{
		tokenService: tokenService,
	}
}

// Auth 认证中间件
func (m *AuthMiddleware) Auth() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 跳过不需要认证的路径
		if isPublicPath(c.Request.URL.Path) {
			c.Next()
			return
		}

		// 获取Token
		token := c.GetHeader("Authorization")
		if token == "" {
			c.JSON(http.StatusUnauthorized, gin.H{
				"code":    401,
				"message": "未授权访问",
			})
			c.Abort()
			return
		}

		// 去掉Bearer前缀
		token = strings.TrimPrefix(token, "Bearer ")

		// 验证Token
		userID, err := m.tokenService.ValidateToken(token)
		if err != nil {
			c.JSON(http.StatusUnauthorized, gin.H{
				"code":    401,
				"message": "无效的Token",
				"error":   err.Error(),
			})
			c.Abort()
			return
		}

		// 将用户ID存储到上下文
		c.Set("user_id", userID)
		c.Next()
	}
}

// isPublicPath 检查是否是公开路径
func isPublicPath(path string) bool {
	publicPaths := []string{
		"/robot/connect",    // WebSocket连接
		"/api/user/login",   // 用户登录
		"/api/user/register", // 用户注册
		"/static/",          // 静态文件
		"/api/health",       // 健康检查
	}

	for _, p := range publicPaths {
		if strings.HasPrefix(path, p) {
			return true
		}
	}
	return false
} 